package com.mashibing.juc.c_002;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName T02_Volatile
 * @Description volatile 并不能保证多个线程共同修改running变量时所带来的不一致问题，
 * volatile不能代替synchronized
 * @Author xiongwei.wu
 * @Date 2021/7/1 11:11
 **/
public class T02_Volatile {
    volatile int count = 0;

    /*synchronized*/ void m() {
        for (int i = 0; i < 10000; i++) {
            count++;
        }
    }

    public static void main(String[] args) {
        T02_Volatile t = new T02_Volatile();

        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(t::m, "thread-" + i));
        }

        threads.forEach(thread -> thread.start());

        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(t.count);
    }
}
